package com.gp.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gp.common.utils.CookieUtils;
import com.gp.common.utils.StringUtil;
import com.gp.mapper.BaseCartMapper;
import com.gp.mapper.BaseOrderMapper;
import com.gp.mapper.BaseOrdergoodsMapper;
import com.gp.mapper.BaseUserrelationMapper;
import com.gp.model.dto.AccountDto;
import com.gp.model.entity.BaseOrder;
import com.gp.model.entity.BaseOrdergoods;
import com.gp.model.entity.BaseUser;
import com.gp.model.entity.BaseUserrelation;
import com.gp.service.IBaseOrdergoodsService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 弓成龙
 * @since 2017-11-26
 */
@Service
public class BaseOrdergoodsServiceImpl extends ServiceImpl<BaseOrdergoodsMapper, BaseOrdergoods>
    implements IBaseOrdergoodsService {

  @Autowired
  private BaseCartMapper cartMapper;
  @Autowired
  private BaseOrdergoodsMapper orderGoodsMapper;
  @Autowired
  private BaseOrderMapper orderMapper;
  @Autowired
  private BaseUserrelationMapper relationMapper;

  /**
   * 结算
   */
  @Override
  public String account(List<AccountDto> account, Object user) {
    // 订单表增加记录
    BaseOrder order = new BaseOrder();
    fillOrderByAccount(order);
    order.setTransportfee("10");
    int current=0;
    for (AccountDto dto : account) {
      // 从购物车中删除该商品
      Map<String, Object> columnMap = new HashMap<String, Object>();
      columnMap.put("userId", ((BaseUser) user).getId());
      columnMap.put("goodsId", dto.getGoodsId());
      cartMapper.deleteByMap(columnMap); 
      // 增加到订单商品表中
      BaseOrdergoods entity = new BaseOrdergoods();
      entity.setOrderCode(order.getOrderCode());
      entity.setGoodsCode(dto.getGoodsId());
      entity.setQuantity(dto.getNumber());
      entity.setPrice(dto.getPrice()+ "");
      current = current + dto.getPrice() * dto.getNumber();
      entity.setTotal(dto.getPrice() * dto.getNumber() + "");
      orderGoodsMapper.insert(entity);
    }
    order.setPlusPrice(current+"");
    orderMapper.insert(order); 
    return order.getOrderCode();
  }

  /**
   * 根据结算信息生成订单表 状态为“未完成” “未支付”
   * @param account 结算信息
   * @param order 需要生成的订单信息
   * @return 生成的订单
   */
  public BaseOrder fillOrderByAccount(BaseOrder order) {
    order.setOrderCode(StringUtil.getUUID());
    BaseUser user = (BaseUser)CookieUtils.obtainCurrentUser(CookieUtils.getCurrentRequest());
    order.setUserPhone(user.getPhone());
    order.setUserCode(user.getId());
    order.setUsername(user.getNickName());
    order.setOrderState("未完成");
    BaseUserrelation entity = new BaseUserrelation();
    entity.setUserCode(user.getId());
    relationMapper.selectOne(entity);
    order.setOperator(entity.getParent() + "");
    order.setPayState(0); // 未支付
    return order;
  }
}
